package muse.schedule;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Scanner;

public class TaskData {
	private static String taskFile = "muse/resources/tasks.mti";
	private static HashMap<String, TaskData> data;
	static {
		data = new HashMap<String, TaskData>();
	}
	public static void loadTasks(ClassLoader cl) {
		try {
			//File f = new File(cl.getResource(taskFile).toURI());
			File f = new File("/home/Phoenix/workspace/Muse/src/muse/resources/tasks.mti");
			Scanner in = new Scanner(f);
			String info = "";
			while(in.hasNext()) {
				String line = in.nextLine();
				if(line.toLowerCase().contains("<task>"))
					info = "";
				else if(line.toLowerCase().contains("</task>")) {
					TaskData container = new TaskData(info);
					data.put(container.getName(), container);
				}
				else info += line + "\n";
			}
			in.close();
		} catch(IOException ex) {
			ex.printStackTrace();
		} //catch (URISyntaxException e) {
			//e.printStackTrace();
		//}
	}
	public static HashMap<String, TaskData>  getData() {
		return data;
	}
	
	private HashMap<String, String> params;
	private String info;
	public TaskData(String info) {
		this.info = info;
		params = new HashMap<String, String>();
		parse(info);
	}
	
	public TaskData cloneMe() {
		TaskData clone = new TaskData(info);
		return clone;
	}
	
	private void parse(String info) {
		String tag = "", val = "";
		Scanner s = new Scanner(info);
		while(s.hasNext()) {
			String line = s.nextLine();
			val += line + "\n";
			if(tag.isEmpty() && line.startsWith("<") && !line.startsWith("</")) {
				int i;
				for(i = 0; i < line.length() && line.charAt(i) != '>'; i++);
				if(i != line.length())
					tag = line.substring(1, i);
			} 
			if(line.endsWith("</" + tag + ">")) {
				val = val.replaceAll("<" + tag + ">", "");
				val = val.replaceAll("</" + tag + ">", "");
				val = val.trim();
				params.put(tag, val);
				tag = "";
				val = "";
			}
		}
		s.close();
	}
	
	public HashMap<String, String> getParams() {
		return params;
	}
	
	public String getName() {
		return params.get("name");
	}
}
